package com.angel.bo.admin.plugin;

import com.angel.bo.admin.service.PermissionService;
import com.angel.bo.auth.client.jwt.AuthUtil;
import com.angel.bo.beans.admin.entity.UserRole;
import com.angel.bo.common.handler.permission.PermissionDialect;
import com.angel.bo.common.msg.WebReturn;
import lombok.extern.slf4j.Slf4j;

import static com.angel.bo.common.util.SpringUtil.getBean;

/**
 * 数据权限处理SQL
 */
@Slf4j
public class SQLPermissionDialect extends PermissionDialect {


    @Override
    public String permissionSql(String sql) {
        PermissionService permissionService = getBean(PermissionService.class);
        WebReturn webReturn ;

        AuthUtil authUtil = getBean(AuthUtil.class);
        UserRole userRole = new UserRole();
        userRole.setUserId(authUtil.getUserIdFromToken());

        webReturn = permissionService.getThePermissionDataByCurrentUser(userRole);

        if(webReturn != null && "".equals(webReturn.getData())){
            return sql;
        }

        StringBuilder sbSql = new StringBuilder(sql);
        sbSql = new StringBuilder("select permissionDataTable.* from (").append(sbSql).append(" ) as permissionDataTable ");
        if(webReturn != null && webReturn.getData() != null){

            sbSql.append(webReturn.getData());
        }
        log.info("权限拼装SQL：{}", sbSql.toString());
        return sbSql.toString();

    }
}
